package com.mobile.web.role;


import com.mobile.service.dto.AuthDTO;
import com.mobile.service.dto.AuthQueryDTO;
import com.mobile.service.dto.RoleDTO;
import com.mobile.service.dto.RoleQueryDTO;
import com.mobile.util.config.aop.AutoFill;
import com.mobile.util.config.aop.OperateType;
import com.mobile.web.base.BaseController;
import com.mobile.web.config.util.Jurisdiction;
import com.mobile.util.RedisUtil;
import com.mobile.service.inter.system.RoleService;
import com.mobile.service.inter.system.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import com.mobile.util.*;

import javax.validation.Valid;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 角色管理API接口
 */
@RestController
@RequestMapping("/role")
public class RoleController extends BaseController {
    @Autowired
    private RoleService roleService;
    @Autowired
    private UserService userService;
    /**
     * 分页查询角色列表
     */
    @RequestMapping("/getRoleListPage")
    //@RequiresPermissions("rolemana:read:1")
    @Operation(
            summary = "分页查询权限",
            description = "根据条件分页查询权限列表，支持模糊查询角色名称"
    )
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "查询成功，返回分页数据"),
            @ApiResponse(responseCode = "400", description = "参数错误（如页码小于1）"),
            @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    public Object getRoleListPage(@Validated RoleQueryDTO roleQueryDTO) {
        Map<String, Object> map = new HashMap<>();

        try {
            PageResult<RoleDTO>  roleList = roleService.getRoleListPage(roleQueryDTO);
            map.put("page", roleList);
            map.put("data", roleList.getPageDatas());
            map.put("QX", Jurisdiction.getHC(this.getUserCode(),"rolemana"));
            map.put(Const.ACTION_RESULT, Const.ACTION_RESULT_SUCCESS);
        } catch (Exception e) {
            map.put(Const.ACTION_RESULT, Const.ACTION_RESULT_EXCEPTION);
            map.put(Const.ACTION_MESSAGE, MessageUtil.getMessage("E0016"));
            logger.error(e.getMessage(), e);
        }

        return AppUtil.returnObject(map);
    }

    /**
     * 根据ID获取角色
     */
    @RequestMapping("/getRoleById")
    //@RequiresPermissions("rolemana:edit:1")
    public Object getRoleById( @Parameter(description = "角色ID", required = true, example = "1001")
                                   @RequestParam("roleId") Integer roleId) {
        Map<String, Object> map = new HashMap<>();

        try {
            RoleDTO role = roleService.getRoleById(roleId);
            map.put("data", role);
            map.put(Const.ACTION_RESULT, Const.ACTION_RESULT_SUCCESS);
            if (StringUtil.isEmpty(role)) {
                map.put(Const.ACTION_RESULT, Const.ACTION_RESULT_FAILED);
                map.put(Const.ACTION_MESSAGE, MessageUtil.getMessage("E0001"));
            }
        } catch (Exception e) {
            map.put(Const.ACTION_RESULT, Const.ACTION_RESULT_EXCEPTION);
            map.put(Const.ACTION_MESSAGE, MessageUtil.getMessage("E0016"));
            logger.error(e.getMessage(), e);
        }

        return AppUtil.returnObject(map);
    }

    /**
     * 获取功能权限树
     */
    @RequestMapping("/getTree")
    //@RequiresPermissions({"rolemana:add:1", "rolemana:edit:1"})
    public Object getTree() {
        Map<String, Object> map = new HashMap<>();
        try {
            List<PageData> tree = roleService.getAuthTree();
            map.put("data", tree);
            map.put(Const.ACTION_RESULT, Const.ACTION_RESULT_SUCCESS);
        } catch (Exception e) {
            map.put(Const.ACTION_RESULT, Const.ACTION_RESULT_EXCEPTION);
            map.put(Const.ACTION_MESSAGE, MessageUtil.getMessage("E0016"));
            logger.error(e.getMessage(), e);
        }
        return AppUtil.returnObject(map);
    }

    /**
     * 新增角色信息
     */
    @RequestMapping("/addRole")
    //@RequiresPermissions("rolemana:add:1")
    @Operation(
            summary = "创建角色",
            description = "新增角色信息，角色名称和编码为必填项"
    )
    @AutoFill(OperateType.INSERT)
    public Object addRole(@Valid RoleDTO roleDTO) {
        Map<String, Object> map;
        try {
            map = roleService.addRole(roleDTO);
        } catch (Exception e) {
            map = new HashMap<>();
            map.put(Const.ACTION_RESULT, Const.ACTION_RESULT_EXCEPTION);
            map.put(Const.ACTION_MESSAGE, MessageUtil.getMessage("E0016"));
            logger.error(e.getMessage(), e);
        }
        return AppUtil.returnObject(map);
    }

    /**
     * 删除角色
     */
    @RequestMapping("/removeRole")
    //@RequiresPermissions("rolemana:delete:1")
    public Object removeRole(@RequestParam("roleId") Integer roleId) {
        Map<String, Object> map = null;

        try {
            map = roleService.removeRole(roleId);
        } catch (Exception e) {
            map = new HashMap<>();
            map.put(Const.ACTION_RESULT, Const.ACTION_RESULT_EXCEPTION);
            map.put(Const.ACTION_MESSAGE, MessageUtil.getMessage("E0016"));
            logger.error(e.getMessage(), e);
        }

        return AppUtil.returnObject(map);
    }

    /**
     * 修改角色
     */
    @RequestMapping("/updateRole")
    //@RequiresPermissions("rolemana:edit:1")
    @Operation(
            summary = "编辑角色",
            description = "编辑角色，角色名称和编码为必填项"
    )
    @AutoFill(OperateType.UPDATE)
    public Object updateRole(@Valid RoleDTO roleDTO) {
        Map<String, Object> map = null;
        Jedis jedis = RedisUtil.getJedis();
        try {
            map = roleService.updateRole(roleDTO,jedis);
        } catch (Exception e) {
            map = new HashMap<>();
            map.put(Const.ACTION_RESULT, Const.ACTION_RESULT_EXCEPTION);
            map.put(Const.ACTION_MESSAGE, MessageUtil.getMessage("E0016"));
            logger.error(e.getMessage(), e);
        }
        jedis.close();
        return AppUtil.returnObject(map);
    }

    /**
     * 查询所有角色信息，前端下拉框用
     */
    @RequestMapping("/getAllRoleList")
    //@RequiresPermissions({"userinfo:add:1", "userinfo:edit:1"})
    public Object getAllRoleList() {
        PageData user = this.getUser();
        Map<String, Object> map = new HashMap<>();

        try {
            List<PageData> roleList = roleService.getAllRoleList(user);
            //查询该用户所有菜单权限
            List<PageData> authTree = userService.getMenuAuthByUser(user.getString("user_code"));
            List<String> authIds = userService.getUserAuthByUserCode(user.getString("user_code"));
            map.put("data", roleList);
            map.put("userRole", user.get("user_role"));
            map.put("authTree", authTree);
            map.put("authIds", authIds);
            map.put(Const.ACTION_RESULT, Const.ACTION_RESULT_SUCCESS);
        } catch (Exception e) {
            map.put(Const.ACTION_RESULT, Const.ACTION_RESULT_EXCEPTION);
            map.put(Const.ACTION_MESSAGE, MessageUtil.getMessage("E0016"));
            logger.error(e.getMessage(), e);
        }

        return AppUtil.returnObject(map);
    }

}
